package com.android.example.app3;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import java.io.File;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UpdateChecker {
    private String TAG = "UpdateChecker";
    private static final String GITEE_API_URL = "https://gitee.com/api/v5/repos/li-guansheng/app3/releases/";
    private static final String OWNER = "liguansheng"; // 替换为你的Gitee用户名
    private static final String REPO = "app3"; // 替换为你的Gitee仓库名
    private static final String TOKEN = "d9d55414937ffc71bd5ce0dff1876a8f"; // 替换为你的Gitee私人令牌
    private OkHttpClient client;
    private GiteeApiHelper.VersionInfoCallback callback;

    private final Context context;

    public UpdateChecker(Context context) {
        this.context = context;
    }

    void checkForUpdates() {


        // 获取版本信息
        String[] versionInfo = VersionUtils.getCurrentVersionInfo(context);
        String versionName = versionInfo[0];
        int versionCode = Integer.parseInt(versionInfo[1]);
        Log.d("UpdateChecker", "Current Version: " + versionName + " (" + versionCode + ")");
        String url = String.format(GITEE_API_URL, OWNER, REPO);
        // 2. 使用Retrofit从服务器获取最新版本信息
        // 创建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(GITEE_API_URL) // 基础URL，根据你的实际情况设置
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 创建UpdateApi接口的实现
        UpdateApi updateApi = retrofit.create(UpdateApi.class);

        // 调用接口方法获取更新信息
        // 使用POJO方式更清晰
        Call<UpdateApi.UpdateInfo> call = updateApi.getLatestUpdateInfoPOJO();


        call.enqueue(new Callback<UpdateApi.UpdateInfo>() {
            @Override
            public void onResponse(@NonNull Call<UpdateApi.UpdateInfo> call, @NonNull Response<UpdateApi.UpdateInfo> response) {
                if (response.isSuccessful() && response.body() != null) {
                    UpdateApi.UpdateInfo updateInfo = response.body();

                    Log.d("UpdateChecker", "Latest Version: " + updateInfo.latestVersionName + " (" + updateInfo.latestVersionCode + ")");
                    Log.d("UpdateChecker", "APK URL: " + updateInfo.apkUrl);

                    // 3. 比较版本
                    if (updateInfo.latestVersionCode > versionCode) {
                        // 有新版本，显示更新对话框
                        showUpdateDialog(updateInfo.latestVersionName, updateInfo.changeLog, updateInfo.apkUrl);
                    } else {
                        Toast.makeText(context, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // 请求成功但响应体为空或解析失败
                    Log.e("UpdateChecker", "Failed to parse update info. Response code: " + response.code());
                    Toast.makeText(context, "无法获取更新信息", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<UpdateApi.UpdateInfo> call, @NonNull Throwable t) {
                // 请求失败（网络问题、服务器不可达等）
                Log.e("UpdateChecker", "Failed to fetch update info", t);
                Toast.makeText(context, "检查更新失败，请检查网络", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void showUpdateDialog(String latestVersionName, String changeLog, String apkUrl) {
        new AlertDialog.Builder(context)
                .setTitle("发现新版本")
                .setMessage("发现新版本 " + latestVersionName + "\n更新内容: " + changeLog)
                .setPositiveButton("立即更新", (dialog, which) -> {
                    downloadApk(apkUrl);
                })
                .setNegativeButton("稍后提醒", null)
                .show();
    }

    private void downloadApk(String downloadUrl) {
        // 5. 使用DownloadManager进行后台下载APK文件
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
        String fileName = "update.apk";
        File downloadDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "");
        File outputFile = new File(downloadDir, fileName);
        request.setDestinationUri(Uri.fromFile(outputFile));

        // 允许在Wi-Fi和移动网络下下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        // 获取DownloadManager实例并开始下载
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (downloadManager != null) {
            long downloadId = downloadManager.enqueue(request);
            // 可以保存downloadId以便后续查询下载状态
        }
    }
}
